#include <iostream>
#include <string>
#include <algorithm>
#include <cmath>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include <TROOT.h>
#include <TFile.h>
#include <TTree.h>
#include <TSQLServer.h>
#include <TSQLResult.h>
#include <TSQLRow.h>
#include <TClonesArray.h>

#include "GeomSvc.h"
#include "TriggerRoad.h"

using namespace std;

TSQLResult *makeQuery(TSQLServer *con, string query)
{
  //cout << query << endl;
  return con->Query(query.c_str());
}

int main(int argc, char **argv)
{
  cout << "Exporting Run: " << argv[1] << " to ROOT file: " << argv[2] << endl;

  Int_t nTracks;

  TFile *saveFile = new TFile(argv[2], "recreate");
  TTree *saveTree = new TTree("save", "save");
 
  saveTree->Branch("nTracks", &nTracks, "nTracks/I");
  
  ///Connect to the SQL databases
  TSQLServer *con = TSQLServer::Connect("mysql://seaquel.physics.illinois.edu", "seaguest","qqbar2mu+mu-");
  const char *buf = "SELECT eventID,count(*) FROM %s.mTrack WHERE zf>630 AND Abs(particleID)=%d GROUP BY eventID";

  char query[500];
  sprintf(query, buf, argv[1], atoi(argv[3])); 
  TSQLResult *res = makeQuery(con, query);

  UInt_t nEntries = res->GetRowCount();
  cout << "Totally " << nEntries << " entries in this run" << endl;
  for(UInt_t i = 0; i < nEntries; i++)
    {
      TSQLRow *row = res->Next();

      nTracks = atoi(row->GetField(1));
      saveTree->Fill();

      delete row;
    }

  delete res;
  delete con;

  saveFile->cd();
  saveTree->Write();
  saveFile->Close();
  
  return 1;
}
